package com.zlq.login.controller;

import com.google.code.kaptcha.Constants;
import com.zlq.login.dao.UserDaoLo;
import com.zlq.login.entity.User;

import javax.servlet.ServletException;
import javax.servlet.annotation.WebServlet;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import javax.sql.DataSource;
import java.io.IOException;
import java.io.PrintWriter;

@WebServlet(urlPatterns = "/loginController")
public class LoginController extends HttpServlet {
    @Override
    protected void doGet(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException {
        //重定向的目的:防止表单重复提交
        resp.sendRedirect("static/login.jsp");
    }

    @Override
    protected void doPost(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException {
        req.setCharacterEncoding("UTF-8");
        resp.setContentType("text/html;charset=UTF-8");
        resp.setCharacterEncoding("UTF-8");

        String name = req.getParameter("name");
        String password = req.getParameter("password");
        String code = req.getParameter("code");

        String scode = (String) req.getSession().getAttribute(Constants.KAPTCHA_SESSION_KEY);
        req.getSession().removeAttribute(Constants.KAPTCHA_SESSION_KEY);


        if (code == null) {
            resp.sendRedirect("/static/login.jsp");
        } else {
            if (!scode.equals(code)) {
                resp.sendRedirect("/static/login.jsp");
            } else {
                if ((!name.isEmpty() || !name.equals(" ")) && (!password.isEmpty() || !password.equals(" "))) {
                    User user = null;
                    try {
                        user = new UserDaoLo().selectByName(name);
                    } catch (Exception e) {
                        e.printStackTrace();
                    }
                    if (user.getName().equals(name) && user.getPassword().equals(password)) {
                        resp.sendRedirect("/static/index.jsp");
                    }
                } else {
                    req.setAttribute("msg","用户名或密码错误！");
                    resp.sendRedirect("/static/login.jsp");
                }
            }
        }
    }
}
